<?php


namespace app\admin\controller;

use app\common\controller\CommonController;
use app\common\controller\platform\Admin;
use app\common\enum\MainEnum;
use app\common\exception\ForbiddenException;
use app\common\middleware\AuthToken;
use app\common\model\UserPlatformTokenModel;
use app\common\model\UserModel;
use app\admin\service\RbacService;
use app\common\service\Lang;
use app\common\validate\UsersValidate;
use app\common\exception\NotFoundException;
use app\common\exception\ParameterFailedException;
use app\common\service\Redis;
use Exception;
use think\facade\Db;
use think\Request;
use think\response\Json;

class AdminController extends CommonController
{
    protected $middleware = [
        AuthToken::class => ['except' => ['loginAdmin']],
    ];

    /**
     * 管理员登陆
     * @return Json
     * @throws Exception
     */
    public function loginAdmin()
    {
        Db::startTrans();
        try {
            $params = self::getParam(
                [
                    'mobile_number',
                    'password',
                ]
            );
            (new UsersValidate())->goCheck(__FUNCTION__, $params);

            $res = Admin::login($params);

            Db::commit();
            //返回token
            return retJson(Lang::LOGINDone, $res);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 重置密码
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/7/7
     * @Time: 14:04
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function repwd()
    {
        //$params = self::getParam(['password', 'repassword', 'repwd_token', 'uid']);
        //(new UsersValidate())->goCheck(__FUNCTION__, $params);
        //
        //$uid   = (int)$params['uid'];
        //$token = Cache::get('user_credential_reset_pwd:'.$uid);
        //if (empty($uid) || empty($token) || $token !== $params['repwd_token']) {
        //    throw new ForbiddenException(['msg' => '您未验证']);
        //}
        //
        //$userModel = UsersModel::findOrEmpty($uid);
        //if ($userModel->isEmpty()) {
        //    throw new NotFoundException(['msg' => '用户不存在']);
        //}
        //$userModel->password = $usersService->set_password($params['password']);
        //if ($userModel->save()) {
        //    Cache::delete('user_credential_reset_pwd:'.$uid);
        //    return retJson('修改成功');
        //} else {
        //    return retJson('修改失败');
        //}
    }

    public function getAdminInfo(Request $request)
    {
        return retJson(Lang::GETDone, $request->userModel->toArray());
    }

    public function putPassword(Request $request)
    {

        $params      = self::getParam(
            [
                'old_password',
                'new_password',
            ]
        );
        (new UsersValidate())->goCheck(__FUNCTION__, $params);

        // 验证账号密码
        $userModel = UserModel::where('id', $request->userModel->getData('id'))->field('id,password,salt')->find();
        if (!$userModel) {
            throw new ForbiddenException(
                [
                    'msg'  => '用户不存在',
                    'code' => MainEnum::ERROR_TOKEN_ERROR,
                ]
            );
        }
        if (!decryptPassword($params['old_password'], $userModel->password, $userModel->salt)) {
            throw new ParameterFailedException(['msg' => '用户名与密码不匹配']);
        }

        $cryptRes            = cryptPassword($params['new_password']);
        $userModel->password = $cryptRes['password'];
        $userModel->salt     = $cryptRes['salt'];
        $userModel->save();

        //返回token
        return retJson(Lang::PUTDone);
    }

    public function putAdminLogout(Request $request)
    {
        Db::startTrans();
        try {
            Admin::loginOut($request);

            Db::commit();
            //返回token
            return retJson(Lang::Done);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }
}